package org.domain.tree.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.validator.NotNull;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;



/**
 * 
 * @author Areshchanka Alexandr
 */

@Entity
@Name("node")
@Scope(ScopeType.SESSION)
@Table(name = "Nodes", uniqueConstraints = @UniqueConstraint(columnNames = {
		"NAME", "PARENT_ID" }))
public class Node implements Serializable{

	private static final long serialVersionUID = -5077387917320053536L;
	
	@Id
    @GeneratedValue
    @Column(name = "NODE_ID")
    private Long id = null;
	
	@Column(name = "NAME", length = 255, nullable = false)
    @NotNull
    private String name;

    @Column(name = "DESCRIPTION", length = 1024)
    @NotNull
    private String description;
    
    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    @JoinColumn(name = "PARENT_ID", nullable = true)
    @org.hibernate.annotations.ForeignKey(name = "FK_PARENT_ID")
    private Node parentNode;
    
    @OneToMany(mappedBy = "parentNode", cascade = { CascadeType.ALL })
    @org.hibernate.annotations.LazyCollection(org.hibernate.annotations.LazyCollectionOption.EXTRA)
    @org.hibernate.annotations.OrderBy(clause = "NAME asc")
    private List<Node> childNodes = new ArrayList<Node>();
    
    /**
	 * This method return count of childs of current node
	 * 
	 * @return count of childs of this node
	 */
    public int getCountChilds() {
        if (this.getChildNodes() != null && this.getChildNodes().toArray().length > 0) {
            return this.getChildNodes().toArray().length;
        }
        return 0;
    }

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Node getParentNode() {
		return parentNode;
	}

	public void setParentNode(Node parentNode) {
		this.parentNode = parentNode;
	}

	public List<Node> getChildNodes() {
		return childNodes;
	}

	public void setChildNodes(List<Node> childNodes) {
		this.childNodes = childNodes;
	}

}
